/**
 * @author banglong
 * @date 2016/8/18.
 */
require.config({
  shim: {
    fetch_detector: ['es6_promise'],
    fetch: ['fetch_detector']
  },
  paths: {
    es6_promise: '../../common/fetch/es6-promise.min',
    fetch_detector: '../../common/fetch/fetch-detector',
    fetch: '../../common/fetch/fetch',
    js_cookie: '../../common/js.cookie',
    rootPath: '../utils/rootPath'
  }
});

define(['es6_promise', 'fetch_detector', 'fetch', 'js_cookie', 'rootPath'],
  function (es, fetch_detector, fetch, cookie, rootPath) {

    if (!Promise) {
      es.polyfill();
    }
    if (!fetch) {
      fetch = window.fetch;
    }

    // 通用的 request 头信息
    var headers = {
      credentials: 'include', // 带上cookie 中间有sessionId 可以在服务器段验证
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: {}
    };

    // 定义 fetch 方法
    var xFetch = function (url, json, isGet) {
      var param;
      if (isGet) {
        delete headers.body;
        param = Object.assign({}, headers, {
          method: 'GET'
        });
      } else {
        param = Object.assign({}, headers, {
          body: JSON.stringify(json)
        });
      }
      return fetch(rootPath.getRootPath() + url, param).then(function (response) {
    	//console.log(response)
    	var json = response.json();
        response = null;
        return json;
      }).then(function (json) {
        // 作为权限判断 当第二个用户登录的时候 或者session过期 那么剔除第一个用户 此时抛出错误0 跳转到登录页
        if (json.isSessionInvalidated) {
          return Promise.reject('0');
        }
        return json
      });
    };
    return xFetch;
  });